package com.b2b.controller;



import com.b2b.model.OrdersDto;
import com.b2b.model.OrdersListDto;
import com.b2b.model.StockDto;
import com.b2b.model.StockSend;
import com.b2b.model.common.CategoryHot;
import com.b2b.model.common.ResponseBean;
import com.b2b.model.entity.Orders;
import com.b2b.model.entity.OrdersGoods;
import com.b2b.model.entity.ReceivingInfo;
import com.b2b.model.entity.company.CompanyInfo;
import com.b2b.model.entity.goods.Goods;
import com.b2b.model.entity.goods.Stock;
import com.b2b.service.*;
import com.b2b.service.goodsService.GoodsService;
import com.b2b.service.goodsService.StockService;

import com.b2b.util.OrdersUtil;
import com.b2b.util.common.StatisticUtil;
import com.b2b.util.common.TimeUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.*;

@RestController
@RequestMapping("/orders")
@CrossOrigin
@PropertySource("classpath:config.properties")
public class OrderController {

    @Value("${refreshTokenExpireTime}")
    private String refreshTokenExpireTime;

    @Autowired
    OrdersService ordersService;

    @Autowired
    ShopService shopService;

    @Autowired
    ReceivingInfoService receivingService;

    @Autowired
    StockService stockService;

    @Autowired
    GoodsService goodsService;

    @Autowired
    OrdersGoodsService ordersGoodsService;

    @Autowired
    CompanyInfoService companyInfoService;

    @Autowired
    OrdersUtil ordersUtil;

    @Autowired
    StatisticUtil statisticUtil;

    @PostMapping("/add")
    public ResponseBean add(@RequestBody OrdersDto ordersDto) throws ParseException {

        Date orderTime = new Date();
        Date expectedDate = TimeUtil.strToDate(ordersDto.getExpectedDate());

        List<StockDto> stockDtoList = ordersDto.getStockList();


        for (StockDto s:stockDtoList
             ) {
            Stock stock = stockService.selectByPrimaryKey(s.getStockId());
            if(stock.getNumber() < s.getNumber())
                return new ResponseBean(HttpStatus.FORBIDDEN.value(), "库存不足", null);
        }


        Integer sellerId = shopService.selectByPrimaryKey(ordersDto.getShopId()).getCompanyId();

        Orders orders = new Orders();
        orders.setOrderTime(orderTime);
        orders.setOrderType(ordersDto.getOrderType());
        orders.setPaymentMode(ordersDto.getPaymentMode());
        orders.setTransportMode(ordersDto.getTransportMode());
        orders.setExpectedDate(expectedDate);
//        orders.setGoodsTotalPrice(ordersDto.getGoodsTotalPrice());
        orders.setFreight(ordersDto.getFreight());
        orders.setDues(ordersDto.getDues());
        orders.setGoodsState('0');
        if(ordersDto.getOrderType().equals('0')) {
            orders.setOrderState('0');
        }else {
            orders.setOrderState('4');
        }
        orders.setBuyerId(ordersDto.getBuyerId());
        orders.setSellerId(sellerId);
        orders.setShopId(ordersDto.getShopId());
        orders.setReceivingInfoId(ordersDto.getReceivingInfoId());

        ordersService.insert(orders);

        Integer orderId = orders.getOrderId();

        List<OrdersGoods> ordersGoodsList = new ArrayList<>();

        for (StockDto  stockDto: stockDtoList
        ) {
            OrdersGoods ordersGoods = new OrdersGoods();
            ordersGoods.setOrderId(orderId);
            ordersGoods.setStockId(stockDto.getStockId());
            ordersGoods.setPrice(stockDto.getPrice());
            ordersGoods.setNumber(stockDto.getNumber());
            ordersGoodsService.insert(ordersGoods);
            ordersGoodsList.add(ordersGoods);
        }

        for (OrdersGoods  o: ordersGoodsList
        ) {
            Stock stock = stockService.selectByPrimaryKey(o.getStockId());
            stock.setNumber(stock.getNumber() - o.getNumber());
            stockService.updateByPrimaryKeySelective(stock);
            o.setOrderId(ordersDto.getOrderId());
        }

        StatisticUtil.updateNumOfOrders(sellerId);

        return new ResponseBean(HttpStatus.OK.value(), "新增成功(Insert Success)", orderId);
    }

    @DeleteMapping("/delete")
    public ResponseBean delete(@RequestParam Integer orderId){
        ordersService.deleteByPrimaryKey(orderId);
        return new ResponseBean(HttpStatus.OK.value(), "删除成功(Delete Success)", null);
    }

    @DeleteMapping("/cancel")
    public ResponseBean cancel(@RequestParam Integer orderId){
        ordersService.deleteByPrimaryKey(orderId);
        OrdersGoods ordersGoods = new OrdersGoods();
        ordersGoods.setOrderId(orderId);
        List<OrdersGoods> ordersGoodsList = ordersGoodsService.select(ordersGoods);
        for (OrdersGoods o:ordersGoodsList
             ) {
            Stock stock = stockService.selectByPrimaryKey(o.getStockId());
            stock.setNumber(stock.getNumber() + o.getNumber());
            stockService.updateByPrimaryKeySelective(stock);
        }
        return new ResponseBean(HttpStatus.OK.value(), "取消成功(Cancel Success)", null);
    }

    @PutMapping("/updateState")
    public ResponseBean updateState(@RequestBody OrdersDto ordersDto){
        Orders orders = new Orders();
        orders.setOrderId(ordersDto.getOrderId());
        if(ordersDto.getOrderState() != null) {
            orders.setOrderState(ordersDto.getOrderState());
        }
        if(ordersDto.getLogisticsNumber() != null && !ordersDto.getLogisticsNumber().equals("")) {
            orders.setLogisticsNumber(ordersDto.getLogisticsNumber());
            orders.setGoodsState('1');
            Orders orders1 = ordersService.selectByPrimaryKey(ordersDto.getOrderId());
            if(orders1.getOrderType() == '0'){
                orders.setOrderState('2');
            }else {
                orders.setOrderState('5');
            }
        }
        ordersService.updateByPrimaryKeySelective(orders);
        return new ResponseBean(HttpStatus.OK.value(), "修改成功(Update Success)", null);
    }

    @PutMapping("/complete")
    public ResponseBean complete(@RequestBody OrdersDto ordersDto){
        Orders orders = new Orders();
        orders.setOrderId(ordersDto.getOrderId());
        ordersService.updateByPrimaryKeySelective(orders);

        OrdersGoods ordersGoods = new OrdersGoods();
        ordersGoods.setOrderId(ordersDto.getOrderId());

        List<OrdersGoods> ordersGoodsList = ordersGoodsService.select(ordersGoods);
        List<CategoryHot> categoryHotList = new ArrayList<>();
        CategoryHot categoryHot = new CategoryHot();
        for (OrdersGoods o:ordersGoodsList
             ) {
            Stock stock = stockService.selectByPrimaryKey(o.getStockId());
            Goods goods = goodsService.selectByPrimaryKey(stock.getGoodsId());
            goods.setSoldTimes(goods.getSoldTimes() + o.getNumber());
            goodsService.updateByPrimaryKeySelective(goods);

            categoryHot.setCategoryId(goods.getCategoryId());
            categoryHot.setSoldTimes(o.getNumber());
            categoryHotList.add(categoryHot);
        }
        statisticUtil.categoryHot(categoryHotList);
        StatisticUtil.updateSalesSum(orders.getSellerId(), orders.getDues());
        return new ResponseBean(HttpStatus.OK.value(), "订单已完成(Order Completed)", null);
    }




    @GetMapping("/getMySold")
    public ResponseBean getMySold(@RequestParam Map<String, Object> map){
        int page = 1, rows = 10;
        if(map.containsKey("page"))
            page = Integer.parseInt(map.get("page").toString());
        if(map.containsKey("rows"))
            rows = Integer.parseInt(map.get("rows").toString());
        PageHelper.startPage(page, rows);
        List<OrdersListDto> ordersListDtoList = new ArrayList<>();
        Orders orders = new Orders();
        OrdersListDto ordersListDto = new OrdersListDto();
        orders.setSellerId(Integer.parseInt(map.get("sellerId").toString()));
        List<Orders> ordersList = ordersService.select(orders);
        for (Orders ordersTemp: ordersList
        ) {
            CompanyInfo companyInfo = companyInfoService.selectByPrimaryKey(ordersTemp.getBuyerId());
            ordersListDto.setOrderId(ordersTemp.getOrderId());
            ordersListDto.setOrderTime(ordersTemp.getOrderTime());
            ordersListDto.setBuyerId(companyInfo.getCompanyId());
            ordersListDto.setBuyerName(companyInfo.getCompanyName());
            ordersListDto.setLogisticsNumber(ordersTemp.getLogisticsNumber());
            ordersListDto.setGoodsTotalPrice(ordersTemp.getGoodsTotalPrice());
            ordersListDto.setFreight(ordersTemp.getFreight());
            ordersListDto.setOrderState(ordersTemp.getOrderState());

            ordersUtil.getOrdersListDtoByOrderId(ordersTemp.getOrderId(), ordersListDto);

            ordersListDtoList.add(ordersListDto);
        }

        PageInfo<OrdersListDto> selectPage = new PageInfo<>(ordersListDtoList);
        Map<String, Object> result = new HashMap<>();
        result.put("count", selectPage.getTotal());
        result.put("ordersList", selectPage.getList());
        return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", result);
    }


    @GetMapping("/getMyBought")
    public ResponseBean getMy(@RequestParam Map<String, Object> map) {
        int page = 1, rows = 10;
        if(map.containsKey("page"))
            page = Integer.parseInt(map.get("page").toString());
        if(map.containsKey("rows"))
            rows = Integer.parseInt(map.get("rows").toString());
        PageHelper.startPage(page, rows);
        List<OrdersListDto> ordersListDtoList = new ArrayList<>();
        Orders orders = new Orders();
        orders.setBuyerId(Integer.parseInt(map.get("buyerId").toString()));
        List<Orders> ordersList = ordersService.select(orders);
        for (Orders ordersTemp: ordersList
             ) {
            OrdersListDto ordersListDto = new OrdersListDto();
            ordersListDto.setOrderId(ordersTemp.getOrderId());
            ordersListDto.setOrderTime(ordersTemp.getOrderTime());
            ordersListDto.setShopId(ordersTemp.getShopId());
            ordersListDto.setShopName(shopService.selectByPrimaryKey(ordersTemp.getShopId()).getShopName());
            ordersListDto.setGoodsTotalPrice(ordersTemp.getGoodsTotalPrice());
            ordersListDto.setFreight(ordersTemp.getFreight());
            ordersListDto.setOrderState(ordersTemp.getOrderState());

            ordersListDtoList.add(ordersUtil.getOrdersListDtoByOrderId(ordersTemp.getOrderId(), ordersListDto));
        }

        PageInfo<OrdersListDto> selectPage = new PageInfo<>(ordersListDtoList);
        Map<String, Object> result = new HashMap<>();
        result.put("count", selectPage.getTotal());
        result.put("ordersList", selectPage.getList());
        return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", result);
    }

    @GetMapping("/getDetail")
    public ResponseBean getDetail(Orders orders){
        orders = ordersService.selectByPrimaryKey(orders.getOrderId());

        ReceivingInfo receivingInfo = receivingService.selectByPrimaryKey(orders.getReceivingInfoId());

        OrdersGoods ordersGoods = new OrdersGoods();
        ordersGoods.setOrderId(orders.getOrderId());
        List<OrdersGoods> ordersGoodsList = ordersGoodsService.select(ordersGoods);
        List<StockSend> stockDtoList = ordersUtil.getStockListByOrdersGoodsList(ordersGoodsList);

        Map<String, Object> result = new HashMap<>();
        result.put("ordersInfo", orders);
        result.put("receivingInfo", receivingInfo);
        result.put("stockList", stockDtoList);
        return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", result);
    }
}
